package com.partvoyage.client;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.api.gwt.client.impl.ClientGoogleApiRequestTransport;
import com.google.api.gwt.client.impl.ClientOAuth2Login;
import com.google.api.gwt.services.plus.shared.Plus;
import com.google.api.gwt.services.plus.shared.Plus.ActivitiesContext.ListRequest.Collection;
import com.google.api.gwt.services.plus.shared.Plus.PlusAuthScope;
import com.google.api.gwt.services.plus.shared.model.Activity;
import com.google.api.gwt.services.plus.shared.model.ActivityFeed;
import com.google.api.gwt.services.plus.shared.model.PeopleFeed;
import com.google.api.gwt.services.plus.shared.model.Person;
import com.google.api.gwt.services.plus.shared.model.PersonPlacesLived;
import com.google.api.gwt.shared.GoogleApiRequestTransport;
import com.google.api.gwt.shared.OAuth2Login;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.partvoyage.client.service.configuration.ConfigurationService;
import com.partvoyage.client.service.configuration.ConfigurationServiceAsync;
import com.partvoyage.shared.ConfigurationBean;
import com.smartgwt.client.widgets.Img;

/**
 * Appelle à Google plus api avec Oauth2
 * 
 * voir
 * http://code.google.com/p/gwt-google-apis/source/browse/trunk/apis/samples
 * /plus/com/google/api/gwt/samples/plus/PlusSample.gwt.xml
 * 
 * http://code.google.com/p/google-plus-java-starter/
 * 
 * Demo code for reading a user's Plus circles. The concrete subclass
 * {@link PlusModule} provides the client-specific usage. This class is suitable
 * for tests or to be used on the server-side.
 */
public class GooglePlusInformation {
	private final static Logger log = Logger
			.getLogger(GooglePlusInformation.class.getName());
	private Plus plus = null;
	private String imageUrl = null;
	private static GooglePlusInformation INSTANCE;
	private ConfigurationBean configurationBean;
	private static final ConfigurationServiceAsync configurationService = GWT
			.create(ConfigurationService.class);

	public static GooglePlusInformation getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new GooglePlusInformation();
		}
		return INSTANCE;

	}

	private GooglePlusInformation() {

	}

	private void connectEtChargeDonnees(OAuth2Login loginImpl,
			final GoogleApiRequestTransport transportImpl, final Img img) {
		loginImpl.withScopes(PlusAuthScope.PLUS_ME).login(
				new Receiver<String>() {
					@Override
					public void onSuccess(String accessToken) {
						initializeTransport(transportImpl, accessToken, img);
					}
				});
	}

	protected void initializeTransport(GoogleApiRequestTransport impl,
			String authorization, final Img img) {
		impl.setAccessToken(authorization)
				.setApplicationName(configurationBean.getApplicationName())
				.setApiAccessKey(configurationBean.getGooglePlusApiKey())
				.create(new Receiver<GoogleApiRequestTransport>() {
					@Override
					public void onSuccess(GoogleApiRequestTransport transport) {
						INSTANCE.plus = GWT.create(Plus.class);
						INSTANCE.plus.initialize(new SimpleEventBus(),
								transport);
						action(INSTANCE.plus, img);
					}
				});
	}

	protected void action(Plus plus, final Img img) {
		// getMe();
		getMyActivities();
		// plus.people().get("me").to(new Receiver<Person>() {
		// @Override
		// public void onSuccess(Person person) {
		// System.out.println(person);
		// if (img != null) {
		// img.setSrc(person.getImage().getUrl());
		// }
		// }
		// }).fire();

	}

	/**
	 * erreur du à json-1.5.jar manquant (je l'ai ajouté dans lib
	 * http://groups.google
	 * .com/group/google-plus-developers/browse_thread/thread
	 * /1def19e27404685/afe0f058365a2bc) connectToPlus(new
	 * ClientOAuth2Login(PlusBase.CLIENT_ID), new
	 * ClientGoogleApiRequestTransport());
	 * 
	 * @param plus
	 */
	public void getMe() {

		plus.people().get("me").to(new Receiver<Person>() {
			@Override
			public void onSuccess(Person person) {
				System.out.println("Hello " + person.getDisplayName());
				System.out.println(person.getImage().getUrl());

			}
		}).fire();
	}

	public void get(String someone) {

		plus.people().get(someone).to(new Receiver<Person>() {
			@Override
			public void onSuccess(Person person) {
				System.out.println("Hello " + person.getDisplayName());
				System.out.println(person.getImage().getUrl());

			}
		}).fire();
	}

	public void getMyActivities() {

//		plus.people().search().setQuery("alfred nguyen")
//				.to(new Receiver<PeopleFeed>() {
//
//					@Override
//					public void onSuccess(PeopleFeed response) {
//						List<Person> persons = response.getItems();
//						if (persons != null) {
//							for (Person person : persons) {
//								System.out.println(person.getDisplayName());
//								get(person.getId());
//
//							}
//						}
//					}
//
//				}).fire();

		plus.activities().list("me", Collection.PUBLIC)
				.to(new Receiver<ActivityFeed>() {
					@Override
					public void onSuccess(ActivityFeed feed) {
						System.out.println("===== PUBLIC ACTIVITIES =====");
						System.out.println(feed.getId());
						if (feed.getItems() == null
								|| feed.getItems().isEmpty()) {
							System.out.println("You have no public activities");
						} else {
							for (Activity a : feed.getItems()) {
								System.out.println(a.getTitle());
							}
						}
					}
				}).fire();
	}

	// protected void actionSearchPeople(Plus plus, final Img img) {
	// plus.people().search().to(new Receiver<PeopleFeed>() {
	//
	// @Override
	// public void onSuccess(PeopleFeed response) {
	// log.info(response);
	//
	// }
	// });
	//
	// }

	public void loadImageUrl(final Img img) {

		// if (INSTANCE.imageUrl == null) {
		if (INSTANCE.plus == null) {
			configurationService
					.getConfiguration(new AsyncCallback<ConfigurationBean>() {
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
						}

						@Override
						public void onSuccess(ConfigurationBean result) {
							configurationBean = result;
							connectEtChargeDonnees(new ClientOAuth2Login(
									configurationBean.getGooglePlusClientId()),
									new ClientGoogleApiRequestTransport(), img);
						}
					});
		} else {
			action(INSTANCE.plus, img);
		}
		// INSTANCE.plus.people().get("me").to(new Receiver<Person>() {
		// @Override
		// public void onSuccess(Person person) {
		// img.setSrc(person.getImage().getUrl());
		// }
		// }).fire();
		// }
		// } else {
		// img.setSrc(INSTANCE.imageUrl);
		// }
	}

	// protected abstract Plus createPlus();
	//
	// protected abstract void println(String value);

	// private HLayout friendHLayout = new HLayout();

	protected void println(String value) {
		// RootLayoutPanel.get().add(new Label(value));

	}
}
